package com.mimo.logic.event.listener;

import java.util.Date;
import java.util.Optional;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import com.mimo.common.comet.dto.ZoneDTO;
import com.mimo.common.configuration.broadcast.listener.EventListener;
import com.mimo.logic.event.UserStatusActionEvent;
import com.mimo.logic.session.model.SessionInfo;
import com.mimo.logic.session.service.ISessionService;
import com.mimo.logic.user.model.UserInfo;
import com.mimo.logic.user.service.IUserService;

@Component
public class UserStatusActionListener implements EventListener<UserStatusActionEvent> {

  @Value("${logic.session.channel}")
  private String topic;

  @Autowired
  private ISessionService sessionService;

  @Autowired
  private IUserService userService;

  @Autowired
  private RedisTemplate<String, String> redisTemplate;

  @Override
  public void onEvent(UserStatusActionEvent event) {
    switch (event.getAction()) {
      case Login:
        Optional<SessionInfo> opt = sessionService.findSessionByUser(event.getUser().getUid());
        if (opt.isPresent()) {// 会话更新
          SessionInfo session = opt.get();
          // Step1 comet端自行维护好用户和它本地的绑定关系,Logic Session部分则直接upsert会话情况
          ZoneDTO zdto = new ZoneDTO();
          BeanUtils.copyProperties(event.getUser().getZone(), zdto);
          session.setZone(zdto);
          session.setLastModifiedDate(new Date());
          sessionService.upsert(session);
        } else {// 新增会话
          sessionService.upsert(this.convert(event.getUser()));
        }
        break;
      case Logout:
        // 会话清除及会话相关房间清除
        sessionService.delete(event.getUser().getUid());
        break;
      case Offline:
        // 会话清除及会话相关房间清除
        sessionService.delete(event.getUser().getUid());

        // 用户状态变更
        userService.logout(event.getUser().getUid());

        // 通知comet 强制断开用户连接
        redisTemplate.convertAndSend(topic, event.getUser().getUid());
        break;
      default:
        throw new IllegalArgumentException("无法处理的用户操作状态");
    }
  }

  private SessionInfo convert(UserInfo user) {
    SessionInfo session = new SessionInfo();
    session.setUid(user.getUid());

    ZoneDTO z = new ZoneDTO();
    BeanUtils.copyProperties(user.getZone(), z);
    session.setZone(z);

    Date now = new Date();
    session.setCreatedDate(now);
    session.setLastModifiedDate(now);

    return session;
  }

}
